<?php //strip
/**
 * Database model for members table.
 *
 * @package odReservationsWpPlugin
 * @subpackage odReservationsWpPlugin_Models
 * @author Ondrej Donek <ondrejd@gmail.com>
 */
class odReservationsWpPlugin_Models_Member extends odWpPlugin_Model_Simple
{
	public function __construct()
	{
		global $wpdb;
		
    parent::__construct(array(
      'tableName'     => $wpdb->prefix . 'reservations_members',
      'primaryColumn' => 'ID',
      'checkColumn'   => 'title',
      'columns'           => array(
        'ID'              => array('type' => 'bigint', 'length' => 20, 'primary' => true),
        'wp_user_ID'      => array('type' => 'bigint', 'length' => 20, 'notnull' => true, 'default' => 0),
        'street'          => array('type' => 'char', 'length' => 255, 'notnull' => true, 'default' => ''),
        'town'            => array('type' => 'char', 'length' => 255, 'notnull' => true, 'default' => ''),
        'zip'             => array('type' => 'char', 'length' => 10, 'notnull' => true, 'default' => ''),
        'phone'           => array('type' => 'char', 'length' => 75, 'notnull' => true, 'default' => ''),
        'member_num'      => array('type' => 'char', 'length' => 75, 'notnull' => true, 'default' => ''),
        'credits_ordered' => array('type' => 'int', 'length' => 10, 'notnull' => true, 'default' => 0),
        'credits_left'    => array('type' => 'int', 'length' => 10, 'notnull' => true, 'default' => 0),
        'created'         => array('type' => 'timestamp', 'notnull' => true, 'default' => 'CURRENT_TIMESTAMP'),
        'deleted'         => array('type' => 'tinyint', 'length' => 1, 'notnull' => true, 'default' => 0)
      )
    ));
	}
	
	/**
	 * Returns members which matches given filter.
	 *
	 * @param string $aFilte
	 * @param number $aCount
	 * @param number $aLimitFrom
	 * @return array|boolean Returns array with members or FALSE.
	 */
	public function select($aFilter = '', $aCount = 0, $aLimitFrom = 0)
	{
		global $wpdb;
		
		$users = parent::select($aFilter, $aCount, $aLimitFrom);
		if(is_null($users)) return array();
    
		foreach($users as $user_key => $user) {
			$wp_user = new WP_User($user['wp_user_ID']);
			$users[$user_key]['login'] = $wp_user->user_login;
			$users[$user_key]['surname'] = $wp_user->last_name;
			$users[$user_key]['firstname'] = $wp_user->first_name;
			$users[$user_key]['email'] = $wp_user->user_email;
      $users[$user_key]['fullname'] = $wp_user->last_name . ', ' . $wp_user->first_name;
		}
		
		return $users;
	}
	
	/**
	 * Check if given login is already used.
	 * 
	 * @param string $aLogin
	 * @return boolean
	 */
	public function checkIfLoginExists($aLogin = '') 
	{
		if(is_null($aLogin) || empty($aLogin)) {
			return false;
		}
		
		global $wpdb;
		
		$query = "SELECT count( `ID` ) FROM `{$wpdb->prefix}users` WHERE `user_login` = '{$aLogin}' ";
		$res = $wpdb->get_col($query);
		
		if(is_array($res)) {
			return ((int) $res[0] == 1) ? true : false;
		}
		
		return false;
	}
	
}
